<template>
  <div class="main">
    <!-- 检索区,查询表单 -->
    <div class="search">
      <!-- 表单组件 -->
      <el-form
        :inline="true"
        ref="searchFromRef"
        :model="sm"
        class="searchForm"
      >
        <!-- 表单项 -->
        <el-form-item label="用户名:" style="width: 200px" prop="loginName">
          <el-input placeholder="请输入用户名" v-model="sm.loginName" />
        </el-form-item>

        <!-- 表单项 -->
        <el-form-item label="昵称：" style="width: 200px" prop="nickName">
          <el-input placeholder="请输入昵称：" v-model="sm.nickName" />
        </el-form-item>
      </el-form>
      <el-button
        color="#909399"
        plain
        :icon="Search"
        @click="search"
        style="width: 75px"
        >查询</el-button
      >
      <el-button
        color="#e6a23c"
        plain
        :icon="Refresh"
        @click="resetSearch"
        style="width: 75px"
        >重置</el-button
      >
    </div>

    <!-- 操作区 -->
    <div class="action">
      <el-button
        color="#409eff"
        plain
        :icon="Plus"
        @click="add"
        style="margin-left: 10px"
        >新增</el-button
      >

      <el-button type="danger" plain :icon="Delete" @click="deleteAll"
        >批量删除</el-button
      >
    </div>

    <!-- 数据展示区 -->
    <div class="data">
      <!-- 表格 -->
      <div class="grid">
        <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="headerCellStyle"
          @row-click="rowClick"
          ref="tableRef"
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="adminId"
            label="ID"
            width="100"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="loginName"
            label="用户名"
            width="200"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="nickName"
            label="昵称"
            width="200"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="200"
            align="center"
            header-align="center"
          />

          <el-table-column
            prop="locked"
            label="是否禁用"
            width="200"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <el-switch
                @change="switchChange2(scope.row)"
                v-model="scope.row.locked"
                class="ml-2"
                :class="
                  scope.row.locked === false
                    ? 'el-switch-enabled'
                    : 'el-switch-disabled'
                "
              />&nbsp;&nbsp;<span v-if="scope.row.locked === true">已禁用</span
              ><span v-if="scope.row.locked === false">已启用</span>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" min-width="200">
            <template #default="scope">
              <el-button
                color="#409eff"
                :icon="Edit"
                style="width: 70px"
                @click="edit(scope.row)"
                plain
                >编辑</el-button
              >
              <el-button
                type="danger"
                plain
                :icon="Delete"
                @click="removeById(scope.row)"
                style="width: 70px"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-pageNum="pageInfo.pageNum"
          v-model:pageNum-size="pageInfo.size"
          :pageNum-sizes="[10, 15, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          background
          @change="paginate"
        />
      </div>
    </div>
  </div>

  <!-- 新增 对话框 -->
  <el-dialog
    v-model="show"
    :title="title"
    width="500"
    draggable
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form ref="sfRef" :model="afm">
      <el-form-item
        label="用户名:"
        label-width="100"
        prop="loginName"
        style="width: 80%"
        :rules="[
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
        ]"
      >
        <el-input v-model="afm.loginName" />
      </el-form-item>

      <el-form-item
        label="昵称:"
        label-width="100"
        prop="nickName"
        style="width: 80%"
      >
        <el-input v-model="afm.nickName" />
      </el-form-item>
    </el-form>

    <el-form-item
      label="密码:"
      label-width="100"
      prop="loginPassword"
      style="width: 80%"
    >
      <el-input v-model="afm.loginPassword" />
    </el-form-item>

    <!-- 对话框按钮，#插槽: 组件空出来，允许用户更改组件内容。由组件使用者定义 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- <h1>{{ sm.birthRange }}</h1> -->
</template>

<script setup>
import adminApi from "@/api/AdminApi";
import { reactive, ref } from "vue";
import { onMounted, toRaw, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
} from "@element-plus/icons-vue";

onMounted(() => {
  search();
  document.title = "植物表型数据管理系统";
});

//响应式对象
const tableData = ref([]);
function paginate() {
  search();
}

// 分页信息
const pageInfo = ref({
  pageNum: 1,
  size: 10,
  total: 0,
});

// 当页码和页码大小改变时触发

function search() {
  let params = sm.value; //查询条件
  adminApi
    .findAll(pageInfo.value.pageNum, pageInfo.value.size, params)
    .then((result) => {
      if (result.code == 0) {
        tableData.value = result.data.list;
        pageInfo.value.total = result.data.total;
        pageInfo.value.pageNum = result.data.pageNo;
        pageInfo.value.size = result.data.pageSize;
        tableData.value.forEach((item) => {
          item.locked = item.locked == 1 ? true : false;
        });
      }
    });
}

// 搜索条表单双向数据绑定
const sm = ref({
  nickName: "",
  loginName: "",
  locked: "",
});

// // 表单实例的引用
let searchFromRef;
function resetSearch() {
  // 重置查询表单
  searchFromRef.resetFields();
}
// 定义表格实例
let tableRef;
//当点击表格时触发
function rowClick(row) {
  tableRef.toggleRowSelection(row);
}

// 删除操作逻辑
function deleteAll() {
  // 从表格中选中的行
  let rows = tableRef.getSelectionRows();
  let ids = []; //id数组
  for (let row of rows) {
    ids.push(row.adminId);
  }
  //执行删除操作
  deleteById(ids);
}
//根据id数组批量删除
function deleteById(ids) {
  console.log(ids);
  // 判断是否选中了要删除的记录
  if (ids.length == 0) {
    ElMessage({
      message: "请选中要删除的记录！",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("是否确定删除选中的记录吗？", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      adminApi
        .removeAll(ids)
        .then((resp) => {
          if (resp.code == 0) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
            search(); //刷新
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "删除操作取消",
          });
        });
    });
  }
}
//  按id删除
function removeById(row) {
  let admit = toRaw(row);
  deleteById([admit.adminId]);
}

// 对话框是否显示
const show = ref(false);

// 定义对话框内容
const adminFormModel = ref({
  loginName: "",
  loginPassword: "",
  nickName: "",
});
// 对话框内容别名
const afm = adminFormModel;

// 对话框标题
const title = ref("新增管理员");
// 弹出新增
function add() {
  show.value = true;
  title.value = "新增管理员";
}
// 提交表单
function submitForm() {
  let admin = afm.value;
  if (admin.adminId) {
    //修改
    submitEdit(admin);
  } else {
    //新增
    submitAdd(admin);
  }
}

// 新增逻辑
function submitAdd(admin) {
  adminApi.save(admin).then((resp) => {
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
}

// 修改操作
function edit(row) {
  let admit = toRaw(row);
  // 浅拷贝
  row = Object.assign({}, admit);
  show.value = true;
  title.value = "修改管理员";
  // 下一个时间滴答中赋值
  nextTick(() => {
    afm.value = row; //给新增/修改表单赋值
  });
}
// 提交表单执行逻辑
function submitEdit(admin) {
  adminApi.update(admin).then((resp) => {
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

//表头样式
function headerCellStyle() {
  return {
    background: " #f4f4f5",
    textAlign: "center",
    color: "#909399",
  };
}

// 切换状态
function switchChange2(row) {
  let admin = toRaw(row);
  user.locked = user.locked === true ? 0 : 1;
  adminApi.updataByState(admin).then((resp) => {
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      // admin.locked = admin.locked === 0 ? 1 : 0;
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
      // 如果修改失败，需要将开关状态还原
      // admin.locked = admin.locked === 0 ? 1 : 0;
    }
  });
}
</script>

<style scoped>
/* 定义不同状态下的 CSS 类 */
.el-switch-enabled {
  --el-switch-on-color: #13c75b;
  --el-switch-off-color: #13c75b;
}
.el-switch-disabled {
  --el-switch-on-color: #f56c6c;
  --el-switch-off-color: #f56c6c;
}
.pagination {
  margin-top: 20px;
}
.search {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.search > form .el-form-item {
  flex-grow: 1;
  margin-right: 10px;
  margin-bottom: 0;
}
.action {
  margin-top: 10px;
  width: 100%;
  display: flex;
  padding: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  margin-top: 20px;
}
.data {
  margin-top: 5px;
  padding: 15px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
